<template>
  <div class="client-evaluation-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2 class="page-title">客户评价</h2>
      <el-button 
        type="primary" 
        size="small" 
        @click="refreshData"
        :loading="loading"
        :icon="Refresh"
      >
        刷新
      </el-button>
    </div>

    <!-- 服务说明 -->
    <div class="service-info">
      <div class="info-header">
        <el-icon class="info-icon"><InfoFilled /></el-icon>
        <span class="info-title">服务说明</span>
      </div>
      <div class="info-content">
        客户评价服务每季度完成一次，对所有客户进行服务质量评价和满意度收集。
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stats-card main-card" @click="goToDetail">
        <div class="card-header">
          <div class="card-title">
            <el-icon class="title-icon"><Star /></el-icon>
            客户评价完成情况
          </div>
          <el-icon class="arrow-icon"><ArrowRight /></el-icon>
        </div>
        <div class="card-content">
          <div class="progress-circle">
            <el-progress 
              type="circle" 
              :percentage="completionPercentage"
              :width="80"
              :stroke-width="8"
              :color="progressColor"
            />
          </div>
          <div class="stats-info">
            <div class="stat-item">
              <div class="stat-number completed">{{ stats.completedCount }}</div>
              <div class="stat-label">已完成</div>
            </div>
            <div class="stat-item">
              <div class="stat-number uncompleted">{{ stats.uncompletedCount }}</div>
              <div class="stat-label">未完成</div>
            </div>
            <div class="stat-item">
              <div class="stat-number total">{{ stats.totalClients }}</div>
              <div class="stat-label">总客户</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 季度进度卡片 -->
      <div class="stats-card quarter-card">
        <div class="card-title">
          <el-icon class="title-icon"><Calendar /></el-icon>
          本季度进度
        </div>
        <div class="quarter-info">
          <div class="quarter-item">
            <span class="quarter-label">当前季度</span>
            <span class="quarter-value">{{ currentQuarter }}季度</span>
          </div>
          <div class="quarter-item">
            <span class="quarter-label">截止时间</span>
            <span class="quarter-value">{{ quarterEndDate }}</span>
          </div>
          <div class="quarter-item">
            <span class="quarter-label">剩余天数</span>
            <span class="quarter-value" :class="{ 'urgent': remainingDays <= 7 }">
              {{ remainingDays }}天
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions">
      <div class="action-title">快速操作</div>
      <div class="action-buttons">
        <el-button 
          class="action-btn"
          @click="goToDetail('completed')"
        >
          <el-icon><Check /></el-icon>
          查看已完成
        </el-button>
        <el-button 
          class="action-btn"
          @click="goToDetail('uncompleted')"
        >
          <el-icon><Warning /></el-icon>
          查看未完成
        </el-button>
        <el-button 
          class="action-btn"
          @click="goToWorkLog"
        >
          <el-icon><Plus /></el-icon>
          添加评价记录
        </el-button>
      </div>
    </div>

    <!-- 最近评价记录 -->
    <div class="recent-records" v-if="recentLogs.length > 0">
      <div class="section-header">
        <h3>最近评价记录</h3>
        <el-button 
          type="primary" 
          text 
          size="small"
          @click="goToWorkLog"
        >
          查看更多
        </el-button>
      </div>
      
      <div class="record-list">
        <div 
          v-for="log in recentLogs.slice(0, 5)" 
          :key="log.id"
          class="record-item"
        >
          <div class="record-info">
            <div class="client-name">{{ log.client.clientName }}</div>
            <div class="record-details">
              <span class="client-code">{{ log.client.clientCode }}</span>
              <span class="record-date">{{ formatDate(log.completionDate) }}</span>
            </div>
            <div class="record-notes" v-if="log.notes">{{ log.notes }}</div>
          </div>
          <div class="record-tags">
            <el-tag size="small" type="success">已评价</el-tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 提醒信息 -->
    <div class="reminder-card" v-if="shouldShowReminder">
      <div class="reminder-header">
        <el-icon class="reminder-icon"><Bell /></el-icon>
        <span class="reminder-title">任务提醒</span>
      </div>
      <div class="reminder-content">
        {{ getReminderMessage() }}
      </div>
      <div class="reminder-actions">
        <el-button size="small" type="primary" @click="goToDetail('uncompleted')">
          立即处理
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Star,
  ArrowRight,
  Calendar,
  Check,
  Warning,
  Plus,
  Bell,
  Refresh,
  InfoFilled
} from '@element-plus/icons-vue'
import { trpc } from '@/utils/trpc'
import { AuthUtils } from '@/utils/auth'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const stats = ref({
  totalClients: 0,
  completedCount: 0,
  uncompletedCount: 0
})
const recentLogs = ref([])

// 计算属性
const completionPercentage = computed(() => {
  const completed = stats.value.completedCount || 0
  const total = stats.value.totalClients || 0
  
  if (total === 0) {
    return completed > 0 ? 100 : 0 // 如果没有总数但有完成数，则为100%
  }
  
  const percentage = Math.round((completed / total) * 100)
  return isNaN(percentage) ? 0 : percentage
})

const progressColor = computed(() => {
  const percentage = completionPercentage.value
  if (percentage >= 80) return '#67c23a'
  if (percentage >= 60) return '#e6a23c'
  return '#f56c6c'
})

const shouldShowReminder = computed(() => {
  return stats.value.uncompletedCount > 0 && (completionPercentage.value < 80 || remainingDays.value <= 7)
})

const currentQuarter = computed(() => {
  const month = new Date().getMonth() + 1
  return Math.ceil(month / 3)
})

const quarterEndDate = computed(() => {
  const year = new Date().getFullYear()
  const quarter = currentQuarter.value
  const endMonth = quarter * 3
  const endDate = new Date(year, endMonth, 0)
  return `${endMonth}月${endDate.getDate()}日`
})

const remainingDays = computed(() => {
  const year = new Date().getFullYear()
  const quarter = currentQuarter.value
  const endMonth = quarter * 3
  const endDate = new Date(year, endMonth, 0)
  const today = new Date()
  const diffTime = endDate.getTime() - today.getTime()
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
})

// 方法
const loadStats = async () => {
  try {
    loading.value = true
    const managerId = getCurrentManagerId()
    if (!managerId) return

    // 获取客户评价服务的ID（从服务列表中查找"客户评价"）
    const serviceList = await trpc.service.list.query({ pageSize: 100 })
    if (!serviceList?.success) throw new Error('加载服务列表失败')
    const services = serviceList.data.data || serviceList.data || []
    const evaluationService = services.find((s: any) => s.serviceName?.includes('客户评价'))
    const evaluationServiceId = evaluationService?.id

    if (!evaluationServiceId) {
      console.warn('未找到客户评价服务')
      stats.value = {
        totalClients: 0,
        completedCount: 0,
        uncompletedCount: 0
      }
      recentLogs.value = []
      return
    }

    // 计算本季度时间范围
    const { startDate, endDate } = getCurrentQuarterRange()

    const result = await trpc.workLog.serviceStats.query({
      managerId,
      serviceId: evaluationServiceId,
      startDate: startDate.toISOString(),
      endDate: endDate.toISOString()
    })

    if (result.success) {
      stats.value = {
        totalClients: result.data.totalClients,
        completedCount: result.data.completedCount,
        uncompletedCount: result.data.uncompletedCount
      }
      recentLogs.value = result.data.recentLogs || []
    }
  } catch (error) {
    console.error('加载客户评价统计失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const getCurrentQuarterRange = () => {
  const now = new Date()
  const quarter = Math.ceil((now.getMonth() + 1) / 3)
  const startMonth = (quarter - 1) * 3
  const startDate = new Date(now.getFullYear(), startMonth, 1)
  const endDate = new Date(now.getFullYear(), startMonth + 3, 0)
  return { startDate, endDate }
}

const refreshData = () => {
  loadStats()
}

const goToDetail = (filter?: string) => {
  router.push({
    name: 'ClientEvaluationDetail',
    query: { 
      period: 'quarter',
      filter: filter || 'all'
    }
  })
}

const goToWorkLog = () => {
  router.push('/work-log')
}

const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

const getReminderMessage = () => {
  if (remainingDays.value <= 7) {
    return `本季度客户评价工作即将截止，还有${remainingDays.value}天！您还有${stats.value.uncompletedCount}户客户未完成评价。`
  }
  return `本季度客户评价工作进度落后，您还有${stats.value.uncompletedCount}户未完成！`
}

const getCurrentManagerId = () => {
  const user = AuthUtils.getUser<any>()
  return user?.id || null
}

// 生命周期
onMounted(() => {
  loadStats()
})
</script>

<style scoped>
.client-evaluation-page {
  background: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.service-info {
  background: #fff7e6;
  border: 1px solid #ffd591;
  margin: 12px;
  border-radius: 8px;
  padding: 16px;
}

.info-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-icon {
  color: #fa8c16;
  margin-right: 8px;
}

.info-title {
  font-size: 14px;
  font-weight: 600;
  color: #fa8c16;
}

.info-content {
  font-size: 13px;
  color: #ad6800;
  line-height: 1.4;
}

.stats-cards {
  padding: 12px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.stats-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.main-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.main-card:active {
  transform: scale(0.98);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.title-icon {
  margin-right: 8px;
  color: #409eff;
}

.arrow-icon {
  color: #c0c4cc;
}

.card-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.progress-circle {
  flex-shrink: 0;
}

.stats-info {
  flex: 1;
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 4px;
}

.stat-number.completed {
  color: #67c23a;
}

.stat-number.uncompleted {
  color: #f56c6c;
}

.stat-number.total {
  color: #409eff;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.quarter-card .card-title {
  margin-bottom: 16px;
}

.quarter-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.quarter-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 6px;
}

.quarter-label {
  font-size: 14px;
  color: #606266;
}

.quarter-value {
  font-size: 14px;
  font-weight: 600;
  color: #409eff;
}

.quarter-value.urgent {
  color: #f56c6c;
}

.quick-actions {
  margin: 12px;
  background: white;
  border-radius: 12px;
  padding: 20px;
}

.action-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  flex: 1;
  height: 44px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  border: 1px solid #dcdfe6;
  background: white;
  color: #606266;
}

.action-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

.recent-records {
  margin: 12px;
  background: white;
  border-radius: 12px;
  padding: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.record-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.record-item {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 8px;
}

.record-info {
  flex: 1;
}

.client-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
}

.record-details {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.record-notes {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
}

.reminder-card {
  margin: 12px;
  background: linear-gradient(135deg, #fff7e6 0%, #fff2d9 100%);
  border: 1px solid #ffd591;
  border-radius: 12px;
  padding: 16px;
}

.reminder-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.reminder-icon {
  color: #fa8c16;
  margin-right: 8px;
}

.reminder-title {
  font-size: 14px;
  font-weight: 600;
  color: #d46b08;
}

.reminder-content {
  font-size: 13px;
  color: #ad6800;
  margin-bottom: 12px;
  line-height: 1.4;
}

.reminder-actions {
  display: flex;
  justify-content: flex-end;
}
</style>
